package com.hmall.trade.listener;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.api.pay.PayClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;


    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(String orderIdStr, Message message) {
        // 1. 获取CorrelationID（从消息头直接获取）
        String correlationId = message.getMessageProperties().getCorrelationId();
        log.info("CorrelationID: {}, 开始处理订单延迟消息", correlationId);

        // 定义锁的名称（使用correlationId作为唯一标识）
        String lockKey = "order-delay-lock:" + correlationId;

        // 尝试获取锁，设置超时时间（防止服务异常导致锁无法释放）
        // 参数说明：waitTime为等待锁的时间，leaseTime为锁的自动释放时间，单位均为毫秒

        log.info("成功获取分布式锁，CorrelationID: {}", correlationId);

        // 1.查询订单
        Long orderId = Long.valueOf(orderIdStr);
        Order order = orderService.getById(orderId);

        // 2.检测订单状态，判断是否已支付
        if (order == null || order.getStatus() != 1) {
            log.info("订单不存在或已支付，CorrelationID: {}", correlationId);
            return;
        }

        log.info("接收到10秒延迟队列消息内容:{}TM:{}, CorrelationID: {}",
                order, LocalDateTime.now(), correlationId);

        // 3.未支付，需要查询支付流水状态
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);

        // 4.判断是否支付
        if (ObjectUtil.isEmpty(payOrderDTO)) {
            // 4.1.已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
            log.info("订单已支付，标记订单为支付成功，CorrelationID: {}", correlationId);
        } else {
            // 4.2.未支付，取消订单，回滚库存
            orderService.cancelOrder(orderId);
            log.info("订单未支付，已取消订单，CorrelationID: {}", correlationId);
        }

    }
}